<template>
	<view class="login-view">
		<van-cell-group>
			<van-field
				:value="state.formData.phone"
				data-name="phone"
				clearable
				label="手机号"
				@change="handleInput"
				placeholder="请输入手机号"
				left-icon="phone-o"
			/>
		</van-cell-group>
		<van-cell-group>
			<van-field
				:value="state.formData.code2"
				clearable
				data-name="code2"
				label="验证码"
				placeholder="请输入短信验证码"
				@change="handleInput"
				left-icon="friends-o"
			>
				<van-button
					@click="getCode"
					slot="button"
					size="small"
					type="info"
					:disabled="state.formData.phone.length < 11"
				>
					{{ state.isShow ? `验证码已发送 ${state.time}s` : '获取验证码' }}
				</van-button>
			</van-field>
		</van-cell-group>
		<view class="botton">
			<van-button :disabled="state.formData.phone.length < 11 || state.formData.code2.length < 6" @click="onSubmit" round type="info" size="large"
				>登陆</van-button
			>
		</view>
	</view>
</template>

<script setup>
// vue3小程序生命周期函数
import { onShareAppMessage, onLoad, onShow, onHide } from '@dcloudio/uni-app'
import { reactive } from 'vue'
import { codeApi, loginApi } from '../../api/modules/user'
import { UserStore } from '../../store/user.js'

const state = reactive({
	formData: {
		phone: '',
		code2: ''
	},
	time: 60,
	isShow: false
})

const userStore = UserStore()

const handleInput = e => {
	const value = e.detail
	const { name } = e.target.dataset
	state.formData[name] = value
}

const getCode = async () => {
	state.isShow = true
	const { data } = await codeApi({ phone: state.formData.phone })
	setTimeout(() => {
		state.formData.code2 = data
	}, 3000)
	let time = setInterval(() => {
		if (state.time <= 0) {
			clearInterval(time)
			state.time = 60
			state.isShow = false
			return
		}
		state.time--
	}, 1000)
}

const onSubmit = async () => {
	await userStore.login(state.formData)
}
// 页面加载
onLoad(message => {})

// 页面显示
onShow(() => {})

// 页面隐藏
onHide(() => {})

// 页面分享(不定义该函数 页面将无法分享)
onShareAppMessage(() => {})
</script>

<style lang="scss">
.login-view {
	padding: 0 24rpx;
	box-sizing: border-box;
	.botton {
		text-align: center;
		margin: 40rpx auto;
		width: 80%;
	}
}
</style>
